package com.cz.nongyetongv5.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.adapter.config.CommonConstants;
import com.cz.nongyetongv5.application.InitApplication;
import com.cz.nongyetongv5.bean.User;
import com.cz.nongyetongv5.custom.dialog.CustomDialog;
import com.cz.nongyetongv5.utils.ConfigUtil;
import com.cz.nongyetongv5.utils.DialogUtil;
import com.cz.nongyetongv5.utils.DownloadDataUtil;
import com.cz.nongyetongv5.utils.DownloadDataUtil.OnLoginEnd;
import com.ronri.ams.SystemEnvironmental;
import com.ronri.ams.bean.loginbean;
import com.ronri.common.UrlEncode;
import com.ronri.common.WaitDialog;
import com.ronri.db.RemoteDataService;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import static com.cz.nongyetongv5.R.layout.login;

public class LoginActivity extends Activity implements OnClickListener,
        TextView.OnEditorActionListener {

    /**
     * 密码输入框
     */
    private EditText edtPassword = null;

    /**
     * 用户名输入框
     */
    private EditText edtUsername = null;

    /**
     * 登陆按钮
     */
    private Button btnLogin = null;

    /**
     * 登陆成功
     */
    public static final int LOGIN_SUCCESS = 0;

    /**
     * 网络异常
     */
    public static final int NO_NETWORK = -1;

    /**
     * 用户不存在
     */

    public static final int USER_UNDEFINED = -2;

    /**
     * 用户信息错误
     */
    public static final int USERINFO_ERROR = -3;

    /**
     * 服务器错误
     */
    public static final int SERVER_ERROR = -4;

    /**
     * 服务器错误2
     */
    public static final int SERVER_ERROR2 = -5;

    /**
     * 登陆等待的对话框
     */
    private CustomDialog waitUserLoginDialog = null;

    /*
     * 不允许登录的框
     */
    private CustomDialog unallowLoginDialog = null;

    /**
     * 验证用户的handler
     */
    private Handler validateUser;

    /**
     * 验证名
     */
    private String validateUsername = null;

    /**
     * 验证密码
     */
    private String validatePassword = null;

    /**
     * 验证的地址
     */
    private String user_isfinedURL = null;

    /**
     * 下载的工具类
     */
    private DownloadDataUtil download = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(login);

        // 取得验证名和验证密码
        validateUsername = new ConfigUtil(getResources()).getRestUsername();

        validatePassword = new ConfigUtil(getResources()).getRestPassword();

        // 连接地址
        user_isfinedURL = getResources().getString(
                R.string.http_request_user_isfined).trim();

        user_isfinedURL = new ConfigUtil(getResources()).getPreHttpUrl()
                + user_isfinedURL;

        // 设置验证名和密码的工具类
        download = DownloadDataUtil.getNewInstance();
        download.setValidateUserName(validateUsername);
        download.setValidatePassword(validatePassword);

        edtPassword = (EditText) LoginActivity.this
                .findViewById(R.id.edtPassword);

        // 当编辑框接受到键盘的动作的时候，键盘的动作往往为下一步,完成等动作Done
        edtPassword.setOnEditorActionListener(this);

        btnLogin = (Button) LoginActivity.this.findViewById(R.id.btnLogin);

        btnLogin.setOnClickListener(this);

        // 查询出用户名和密码的控件
        edtUsername = (EditText) findViewById(R.id.edtUsername);

        edtPassword = (EditText) findViewById(R.id.edtPassword);

        /**
         * 验证用户的handler
         */
        validateUser = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case LOGIN_SUCCESS:
                        // 登陆成功进行跳转
                        // 窗口关闭
                        if (waitUserLoginDialog != null
                                && waitUserLoginDialog.isShowing()) {
                            waitUserLoginDialog.dismiss();
                        }

                        if (msg.obj != null && msg.obj instanceof User) {

                            User user = (User) msg.obj;

                            ConfigUtil configUtil = new ConfigUtil(getResources());

                            boolean canLogin = configUtil.containerRegionCode(user
                                    .getKnowRegion() + "");

                            if (!canLogin) {

                                unallowLoginDialog = DialogUtil.showMessageDialog(
                                        "非法账号,禁止登陆!", new OnClickListener() {

                                            @Override
                                            public void onClick(View v) {

                                                unallowLoginDialog.dismiss();

                                            }
                                        }, LoginActivity.this);

                                return;

                            }

                            // 进行界面的跳转
                            Intent to_main_intent = new Intent(LoginActivity.this,
                                    MainActivity.class);
                            // 将数据传递到下一个页面
                            to_main_intent.putExtra("user", user);

                            startActivity(to_main_intent);

                            finish();

                        }

                        break;

                    case NO_NETWORK:
                        // 网络连接失败,显示对话框,网络连接失败!
                        showMessageDialog(getResources().getString(
                                R.string.error_no_network));

                        if (waitUserLoginDialog != null
                                && waitUserLoginDialog.isShowing()) {

                            waitUserLoginDialog.dismiss();
                        }

                        break;

                    case USER_UNDEFINED:

                        // 显示用户不存在
                        showMessageDialog(getResources().getString(
                                R.string.message_user_undefined));

                        // 用户不存在
                        // 进行光标的定位
                        edtUsername.setFocusable(true);
                        edtUsername.requestFocus();
                        edtUsername.selectAll();

                        if (waitUserLoginDialog != null
                                && waitUserLoginDialog.isShowing()) {

                            waitUserLoginDialog.dismiss();
                        }

                        break;
                    case USERINFO_ERROR:

                        // 显示密码不正确
                        showMessageDialog(msg.obj.toString());

                        // 用户名或者密码错误
                        edtPassword.setFocusable(true);
                        edtPassword.requestFocus();
                        edtPassword.selectAll();

                        if (waitUserLoginDialog != null
                                && waitUserLoginDialog.isShowing()) {

                            waitUserLoginDialog.dismiss();
                        }
                        break;

                    case SERVER_ERROR:

                        // 显示密码不正确
                        showMessageDialog(msg.obj.toString());

                        // 用户名或者密码错误
                        edtPassword.setFocusable(true);
                        edtPassword.requestFocus();
                        edtPassword.selectAll();

                        if (waitUserLoginDialog != null
                                && waitUserLoginDialog.isShowing()) {

                            waitUserLoginDialog.dismiss();
                        }

                        break;

                    case SERVER_ERROR2:

                        Toast.makeText(
                                LoginActivity.this,
                                getResources().getString(
                                        R.string.message_userinfo_servererror2),
                                Toast.LENGTH_LONG).show();
                        if (waitUserLoginDialog != null
                                && waitUserLoginDialog.isShowing()) {

                            waitUserLoginDialog.dismiss();
                        }
                        break;

                }

            }

        };

    }

    // 按钮点击事件
    @Override
    public void onClick(View v) {

        // 点击登陆的时候
        if (v == btnLogin) {

            // 进行登录处理
            doLogin();
        }

    }

    // 当接受到键盘的动作所触发的事件
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

        // 当键盘的动作ID 是 指定ID的时候,这里是DONE,相当于点击了登陆按钮
        if (actionId == EditorInfo.IME_ACTION_DONE) {

            // 登陆
            doLogin();
        }

        return false;
    }

    // 处理登陆的方法
    private void doLogin() {

        /**
         * 初始化对话框
         */
        waitUserLoginDialog = new CustomDialog(LoginActivity.this);

        waitUserLoginDialog = new CustomDialog(this);
        waitUserLoginDialog.setMessage(getResources().getString(
                R.string.message_loginning));

        waitUserLoginDialog.setCanceledOnTouchOutside(false);

        waitUserLoginDialog.setWidthPercent(0.6F);

        waitUserLoginDialog.setTitle(null);

        waitUserLoginDialog.setActionTxt(null);

        waitUserLoginDialog.setCancleTxt(null);

        // 取得用户名和密码
        final String username = edtUsername.getText().toString().trim();
        final String password = edtPassword.getText().toString().trim();

        //执行新程序的登录
        //		Logon(username,password);

        // 处理获取用户信息的线程
        Thread userLoginThread = new Thread(new Runnable() {
            @Override
            public void run() {
                download.login(username, password, user_isfinedURL,
                        LoginActivity.this, new OnLoginEnd() {
                            @Override
                            public void onLoginEnd(User user, int stateCode) {

                                if (stateCode == LoginActivity.LOGIN_SUCCESS
                                        && user != null) {
                                    Message message = new Message();
                                    message.what = stateCode;
                                    message.obj = user;
                                    validateUser.sendMessage(message);

                                    /**
                                     * 登陆成功后将用户的信息保存下来
                                     */
                                    // 数据分享
                                    SharedPreferences sharedData = LoginActivity.this
                                            .getSharedPreferences(
                                                    CommonConstants.SHARED_REFERENCES_TAG,
                                                    Context.MODE_PRIVATE);

                                    Editor editor = sharedData.edit();

                                    editor.putString("account", user.getUsername());

                                    editor.putString("username",
                                            user.getUsername());

                                    editor.putString("realname",
                                            user.getRealname());

                                    editor.putString("password",
                                            user.getPassword());

                                    editor.putString("town_path_id",
                                            user.getTown_path_id());

                                    editor.putString("showname",
                                            user.getShowname());

                                    editor.putString("localpysimple",
                                            user.getLocalPySimple());

                                    editor.putString("region_longitude",
                                            user.getRegion_longitude() + "");

                                    editor.putString("region_latitude",
                                            user.getRegion_latitude() + "");

                                    editor.putInt("region_zoom",
                                            user.getRegion_zoom());

                                    editor.putBoolean("tester", user.isTester());
                                    editor.putString("region_name",
                                            user.getRegion_name());
                                    // 提交数据修改
                                    editor.commit();

                                } else {

                                    if (user == null) {

                                        user = new User();
                                    }

                                    if (stateCode == LoginActivity.USER_UNDEFINED) {
                                        user.setMessage("用户不存在...");
                                    }
                                    if (stateCode == LoginActivity.SERVER_ERROR) {

                                        user.setMessage("服务器返回错误..");

                                    }
                                    if (stateCode == LoginActivity.NO_NETWORK) {

                                        user.setMessage("没有连接网络..");
                                    }

                                    // 发送改变状态
                                    Message message = new Message();
                                    message.what = stateCode;
                                    message.obj = user.getMessage();
                                    validateUser.sendMessage(message);
                                }

                            }
                        });
            }
        });

        if (username != null && !"".equals(username) && password != null
                && !"".equals(password)) {
            waitUserLoginDialog.showWait();
            userLoginThread.start();
        } else {
            // 请输入用户名和密码
            Toast.makeText(
                    LoginActivity.this,
                    getResources().getString(
                            R.string.message_userinfo_inputnull),
                    Toast.LENGTH_LONG).show();

        }
    }

    /**
     * 弹出信息框
     */
    private void showMessageDialog(String message) {

        final CustomDialog messageDialog = new CustomDialog(LoginActivity.this);
        messageDialog.setMessage(message);

        messageDialog.setOnActionClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                messageDialog.dismiss();
            }
        });

        messageDialog.setActionTxt(getResources().getString(
                R.string.jiandujiancha_btn_sureitem));

        messageDialog.show();

    }

    private void showMessage(String message) {

        Toast.makeText(LoginActivity.this, message, Toast.LENGTH_SHORT).show();

    }

    /***
     * 登录处理
     * @param szAcc
     * @param szPwd
     */
    private void Logon(final String szAcc, final String szPwd) {
        RemoteDataService remoteDataService = new RemoteDataService();

        // 获取远程地址
        String szRemoteAddress = InitApplication.SystemConfig.getBase().RemoteAddress(
                InitApplication.SystemConfig.getModule().getLogin().getAddress());
        Map<String, Object> mParam = new HashMap<String, Object>();

        try {
            mParam.put("addFrom", 1);
            mParam.put("addMark", "android");
            //			mParam.put("account","test_zj");
            //			mParam.put("password", "111111");
            mParam.put("account", URLEncoder.encode(szAcc, "utf-8"));
            mParam.put("password", URLEncoder.encode(szPwd, "utf-8"));
            mParam.put("deviceid", "?????");
        } catch (Exception ex) {

        }

        // 获取远程数据
        remoteDataService.getRemoteData(szRemoteAddress,
                UrlEncode.getUrlParamsByMap(mParam, false),
                InitApplication.SystemConfig.getModule().getLogin().getMethod(),
                new RemoteDataService.OnRemoteDataEvent() {
                    // 返回结果
                    @Override
                    public void OnResultEvent(String szString) {
                        SharedPreferences sharedData = LoginActivity.this
                                .getSharedPreferences(
                                        CommonConstants.SHARED_REFERENCES_TAG,
                                        Context.MODE_PRIVATE);

                        if (szString.isEmpty())
                            return;

                        try {
                            loginbean login = JSON.parseObject(szString, loginbean.class);

                            if (login.isSuccess()) {

                                SharedPreferences.Editor editor = sharedData.edit();

                                editor.putString("account", szAcc);
                                editor.putString("password", szPwd);
                                editor.putBoolean("autologin", true);

                                editor.putString("loginInfo", szString);
                                editor.commit();

                                // 记录登录信息
                                InitApplication.LoginInfo = login;

                            } else {
                                SharedPreferences.Editor editor = sharedData.edit();

                                editor.putString("account", "");
                                editor.putString("password", "");
                                editor.putBoolean("autologin", false);
                                editor.commit();

                                // 提示错误信息
                                WaitDialog.ShowDialog(LoginActivity.this, login.getMessage());
                                Thread.sleep(3000);
                                WaitDialog.HideDialog();
                            }
                        } catch (Exception ex) {

                        }
                    }

                    // 状态控制，是否显示加载过程
                    @Override
                    public void OnRuningState(int nStatus) {
                        if (nStatus == SystemEnvironmental.StartGetDataFromServer) {
                            WaitDialog.ShowDialog(LoginActivity.this, "正在验证，请稍后...");
                        } else {
                            if (nStatus == SystemEnvironmental.StopGetDataFromServer) {
                                WaitDialog.HideDialog();
                            } else {
                                if (nStatus == SystemEnvironmental.GetDataFromServerError) {
                                    // 提示错误信息
                                    WaitDialog.ShowDialog(LoginActivity.this, "网络连接错误！");
                                    try {
                                        Thread.sleep(3000);
                                    } catch (Exception ex) {
                                    }
                                    WaitDialog.HideDialog();
                                }
                            }
                        }
                    }

                    @Override
                    public String OnGetCustomParam() {
                        return null;
                    }
                });
    }
}
